<?php

/**
 * This is the MongoDB Document model class based on table "admin".
 */
class Admin extends EMongoDocument
{

    public $_id;
    public $username;
    public $password;

    /**
     * Returns the static model of the specified AR class.
     * @return Admin the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * returns the primary key field for this model
     */
    public function primaryKey()
    {
        return '_id';
    }

    /**
     * @return string the associated collection name
     */
    public function getCollectionName()
    {
        return 'admin';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('username, password', 'required'),
            array('username', 'length', 'max' => 12),
            array('password', 'length', 'max' => 32),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('_id, username, password', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            '_id' => 'ID',
            'username' => '用户名',
            'password' => '密码',
        );
    }

     /* mongodb生成自增id
     * @author  RenLong
     * @date  2013-09-25
     * @param  $model
     * @return string
     * 
     * 解决mongodb无自增ID思路：
     * 数据库中查找最新一条记录的ID值，
     * 如ID不存在，赋ID值为1；
     * 如存在，则读取ID值并加1，返回新值。
     * 
     * 第一种写法
     * $criteria = new EMongoCriteria();
     * $criteria->sort('_id', EMongoCriteria::SORT_DESC);
     *
     * 第二种写法
     */

    public function auto_id($model)
    {
        $a = array('sort' => array('_id' => EMongoCriteria::SORT_DESC));
//        var_dump($a);exit;
        $criteria = new EMongoCriteria($a);
        $data = $model->findAll($criteria);
//        var_dump($data);exit;
        if ($data)
        {
            $id = $data[0]->id;
            $id++;
        }
        else
        {
            $id = 1;
        }

        //必须int转为string，否则$this->loadModel无法查询，返回为null.
        return (string) $id;
    }

}